import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import DataEditTable from '../addons/DataEditTable'
import TMinDiviFrom from './TMinDiviFrom'
import * as compDiviService from '../../services/AccountDivi';
const daoName = "MinOper";
const ButtonGroup = Button.Group;
const columns = [
    { title: '交易日期', width: 110, sorter: true, key: 'TRTD', caption: "TRTD", render: data => datetime.format(data.TRTD, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '营业网点', width: 110, sorter: true, dataIndex: 'OrganName', key: 'OrganName', dispaly: true, filter: true },
    { title: '种类码', width: 140, sorter: true, dataIndex: 'CHTP', key: 'CHTP', dispaly: true, filter: true },
    { title: '科目', width: 100, sorter: true, dataIndex: 'ITNM', key: 'ITNM', dispaly: true, filter: true },
    { title: '收费名称', width: 215, sorter: true, dataIndex: 'CHNM', key: 'CHNM', dispaly: true, filter: true },
    { title: '付款帐号', width: 215, sorter: true, dataIndex: 'ACNO', key: 'ACNO', dispaly: true, filter: true },
    { title: '付款户名', width: 260, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
    { title: '单位笔数', width: 110, sorter: true, dataIndex: 'TRCT', key: 'TRCT', dispaly: true, filter: true },
    { title: '收费总额', width: 110, sorter: true, dataIndex: 'HDCH', key: 'HDCH', dispaly: true, filter: true },
    { title: '状态', width: 110, sorter: true, dataIndex: 'ACTP', key: 'ACTP', dispaly: true, filter: true },
    { title: '中间业务类型', width: 180, sorter: true, dataIndex: 'ITNM3', key: 'ITNM3', dispaly: true, filter: true },
];
const columnsDv = [
    { title: '交易日期', width: 110, sorter: true, key: 'TRTD', caption: "TRTD", render: data => datetime.format(data.TRTD, "yyyy-MM-dd"), dispaly: true, filter: true },
    { title: '营业网点', width: 110, sorter: true, dataIndex: 'OrganName', key: 'OrganName', dispaly: true, filter: true },
    { title: '科目', width: 180, sorter: true, dataIndex: 'ITNM', key: 'ITNM', dispaly: true, filter: true },
    { title: '付款帐号', width: 230, sorter: true, dataIndex: 'ACNO', key: 'ACNO', dispaly: true, filter: true },
    { title: '付款户名', width: 220, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
];
const controls = [
    { name: 'TRTD', required: true, type: 'date', label: '交易日期',dataType: "date", min: 1, max: 50, grid: 12 / 24 },
    { name: 'OrganName', required: true, type: 'text', label: '营业网点', min: 1, max: 50, grid: 12 / 24 },
    { name: 'CHTP', required: true, type: 'text', label: '种类码', min: 1, max: 50, grid: 12 / 24 },
    { name: 'ITNM', required: true, type: 'text', label: '科目', min: 1, max: 50, grid: 12 / 24 },
    { name: 'CHNM', required: true, type: 'date', label: '收费名称',  grid: 12 / 24 },
    { name: "ACNO", required: true, type: 'text', label: '付款帐号', min: 1, max: 50, grid: 12 / 24 },
    { name: "CUNM", required: true, type: 'number', label: '付款户名', dataType: "number", grid: 12 / 24 },
    { name: 'TRCT', required: true, type: 'text', label: '单位笔数', min: 1, max: 50, grid: 12 / 24 },
    { name: 'HDCH', required: true, type: 'text', label: '收费总额', min: 1, max: 50, grid: 12 / 24 },
    { name: 'ACTP', required: true, type: 'text', label: '状态', min: 1, max: 50, grid: 12 / 24 },
    { name: 'ITNM3', required: true, type: 'text', label: '中间业务类型', min: 1, max: 50, grid: 12 / 24 },
];
const columnsFhDivi = [
    { title: 'EMID', sorter: true, key: 'EMID', dataIndex: 'EMID', dispaly: false, filter: false },
    { title: '工号', width: 100, sorter: true, key: 'EMNO', dataIndex: 'EMNO', dispaly: true, filter: true },
    { title: '员工姓名', width: 100, sorter: true, key: 'EMNM', dataIndex: 'EMNM', dispaly: true, filter: true },
    { title: '部门名称', width: 120, sorter: true, key: 'OrganName', dataIndex: 'OrganName', dispaly: true, filter: true },
    { title: '分户比例', width: 100, sorter: true, dataIndex: 'DSVL', key: 'DSVL', dispaly: true, filter: true },
    { title: '分户日期', width: 100, sorter: true, key: 'DSDT', caption: "DSDT", render: data => datetime.format(data.DSDT, "yyyy-MM-dd"), dispaly: true, filter: true, canEdit: true },
];
const controlsFhDivi = [
    { name: 'EMNO', required: true, type: 'text', min: 1, max: 50, label: '工号', grid: 12 / 24 },
    { name: 'EMNM', required: true, type: 'text', label: '员工姓名', min: 1, max: 50, grid: 12 / 24 },
    { name: 'OrganName', required: true, type: 'text', label: '部门名称', min: 1, max: 50, grid: 12 / 24 },
    { name: 'DSVL', required: true, type: 'number', label: '分户比例', grid: 12 / 24, dataType: "number" },
    { name: 'DSDT', required: true, type: 'date', label: '分户日期', grid: 12 / 24, dataType: "date" },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class TMinOperFrom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            diviList: {},
            seachData: {},
            seachDataSource: [],
            diviDisplay: {
              div1: 'none',
              div2: '',
              lable: '认定',
              isRD: true
            }, 
        };
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.selectedRowKeys.length !== this.props.selectedRowKeys.length) {
            nextProps.selectedRowKeys.map(key => {
                for (let i = 0; i < nextProps.list.length; i++) {
                    if (nextProps.list[i]["ID"] === key) {
                        this.state.diviList[key] = { ...nextProps.list[i] };
                        break;
                    }
                }
            })
        }
    }
    deleteHandle(delDatas) {
        let selkeys = [...this.props.selectedRowKeys]
        for (let j = delDatas.length - 1; j >= 0; j--) {
            const key = delDatas[j]["ID"]
            delete this.state.diviList[key]
            const index = selkeys.indexOf(key)
            if (index !== -1) {
                selkeys.splice(index, 1)
            }
        }
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: selkeys }
        });
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID" }
        });
        let whereItems = [];
        let WhereCauses = [];
        whereItems.push({
            FieldName: "NTPN1",
            Operator: "=",
            FieldValues: '1'
        })
        WhereCauses.push({
            WhereItems: whereItems,
            RelationSign: "AND"
        })
        let seeks=WhereCauses

        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20,seeks }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showDiviHandler() {
        if (this.state.diviDisplay.isRD) {
            this.state.diviDisplay.div1='';
            this.state.diviDisplay.div2='none';  
            this.state.diviDisplay.lable = '返回';
            this.state.diviDisplay.isRD = false;
          } else {
              this.state.diviDisplay.div1 = 'none';
              this.state.diviDisplay.div2 = '';
              this.state.diviDisplay.lable = '认定';
              this.state.diviDisplay.isRD = true;
          }
        this.state.diviList = {};
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    addSeachDiviHandler() {
        let dsvl = 0
        let dsdt = "";
        const form = this.refs.TMinDiviFrom.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                if (values.EMID !== "" && values.DSVL !== "" && values.DSDT !== "") {
                    dsvl = values.DSVL
                    dsdt = values.DSDT === !values.DSDT ? null : new Date(values.DSDT.get("year"), values.DSDT.get("month"), 1, 8, 0, 0)
                }
            }
        })
        if (dsvl === "" || dsvl === 0) {
            message.error('分配比例失败！比例不能为空且不能为零,请输入比例！');
            return;
        } else if (dsdt === "") {
            message.error('分配比例失败！日期不能为空,请选择日期！');
            return;
        }
        let data = {
            EMID: this.state.seachData.ID,
            EMNO: this.state.seachData.No,
            EMNM: this.state.seachData.Name,
            OrganName: this.state.seachData.Organization.Name,
            DSVL: dsvl,
            DSDT: dsdt
        }
        let dataSource = this.refs.diviFhTable.state.datas;
        let sumDsvl = 0;
        //验证：添加的员工是否重复，并累加已分配比例是否超出100%
        for (let i = 0; i < dataSource.length; i++) {
            if (Number(dataSource[i]["EMID"]) === Number(data["EMID"])) {
                message.error('分配比例失败！所选员工已分配，请重新选择员工分配！');
                return;
            } else {
                sumDsvl = Number(sumDsvl) + Number(dataSource[i]["DSVL"])
            }
        }
        //验证：已分配比例和新分配比例之和是否超出100%
        let sum = Number(sumDsvl) + Number(data.DSVL)
        if (sum <= 100) {
            dataSource.push(data)
        } else {
            message.error('分配比例失败！已分配比例满足100%或分配比例超出剩余分配比例，请核对分配比例！');
            return;
        }
        this.setState({ seachDataSource: dataSource })
    }
    deleteSeachDiviHandler() {
        const keys = this.refs.diviFhTable.getSelectRowKeys();
        let datas = this.refs.diviFhTable.state.datas;
        let total = this.refs.diviFhTable.state.total;
        let indexs = []
        const keyName = "EMID"
        datas.map((d, k) => {
            for (let i = 0; i < keys.length; i++) {
                if (d[keyName] === keys[i]) {
                    indexs.push(k)
                    total--
                }
            }
        })
        let delDatas = this.refs.diviFhTable.state.delDatas
        for (let j = indexs.length - 1; j >= 0; j--) {
            const k = indexs[j]
            if (datas[k].$state !== 1) {
                delDatas.push(datas[k])
            }
            datas.splice(k, 1)
        }
        this.setState({ seachDataSource: datas })
    }
    submitSeachDiviHandler() {
        const datas = this.refs.diviFhTable.state.datas;
        const witDividatas = this.refs.diviTable.state.datas;
        if (witDividatas.length <= 0) {
            message.info('请选择要认定的账户!');
            return;
        }
        let dsvlSum = 0;
        let dataSource = []
        datas.map(d => {
            dsvlSum = Number(dsvlSum) + Number(d.DSVL);
            let data = {
                EMID: Number(d.EMID),
                DSDT: d.DSDT,
                DSVL: Number(d.DSVL) / 100
            }
            dataSource.push(data);
        })
        if (dsvlSum !== 100) {
            message.info('占比必须为100%');
            return;
        }
        let acids = [];
        witDividatas.map(d => acids.push(Number(d.ID)))
        compDiviService.clieMinDivi({ acids, dataSource }
        ).then(function (data) {
        }).catch(function (ex) {
            console.log('请求出错', ex)
        });        
        this.state.diviDisplay.div1 = 'none';
        this.state.diviDisplay.div2 = '';
        this.state.diviDisplay.lable = '认定';
        this.state.diviDisplay.isRD = true;
        this.state.seachDataSource = [];
        this.state.diviList = {};
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    }
    showTableHandler() {
        let ACNO = "";
        let CUNM = "";
        let TRTD ="";
        let seeks = [];
        const form = this.refs.TMinOperFrom.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                if (values.ACNO === undefined) {
                    values.ACNO = "";
                }
                if (values.CUNM === undefined) {
                    values.CUNM = "";
                }
                if (values.TRTD !== null) {
                    let td =new Date(values.TRTD);
                    let month = td.getMonth()+1;
                    TRTD=td.getFullYear()+'-'+month+'-'+td.getDate()
                }
                ACNO = values.ACNO;
                CUNM = values.CUNM;
            }
        })
        let whereItems = [];
        let WhereCauses = [];
        if (ACNO !== "" && CUNM !== "" && TRTD!=="") {
            whereItems.push({
                FieldName: "ACNO",
                Operator: "like",
                FieldValues: ACNO
            });
            whereItems.push({
                FieldName: "CUNM",
                Operator: "like",
                FieldValues: CUNM
            });
            whereItems.push({
                FieldName: "TRTD",
                Operator: "=",
                FieldValues: TRTD
            })
        } else if (ACNO !== "" && CUNM === "" && TRTD==="") {
            whereItems.push({
                FieldName: "ACNO",
                Operator: "like",
                FieldValues: ACNO
            });
        } else if (ACNO === "" && CUNM !== "" && TRTD==="") {
            whereItems.push({
                FieldName: "CUNM",
                Operator: "like",
                FieldValues: CUNM
            })
        }  else if (ACNO === "" && CUNM === "" && TRTD!=="") {
            whereItems.push({
                FieldName: "TRTD",
                Operator: "=",
                FieldValues: TRTD
            })
        }  else if (ACNO !== "" && CUNM !== "" && TRTD==="") {
            whereItems.push({
                FieldName: "ACNO",
                Operator: "like",
                FieldValues: ACNO
            });
            whereItems.push({
                FieldName: "CUNM",
                Operator: "like",
                FieldValues: CUNM
            })
        } else if (ACNO !== "" && CUNM === "" && TRTD!=="") {
            whereItems.push({
                FieldName: "ACNO",
                Operator: "like",
                FieldValues: ACNO
            });
            whereItems.push({
                FieldName: "TRTD",
                Operator: "=",
                FieldValues: TRTD
            })
        }else if (ACNO === "" && CUNM !== "" && TRTD!=="") {
            whereItems.push({
                FieldName: "CUNM",
                Operator: "like",
                FieldValues: CUNM
            });
            whereItems.push({
                FieldName: "TRTD",
                Operator: "=",
                FieldValues: TRTD
            })
        }
        whereItems.push({
            FieldName: "NTPN1",
            Operator: "=",
            FieldValues: '1'
        })
        WhereCauses.push({
            WhereItems: whereItems,
            RelationSign: "AND"
        })
        if (whereItems.length !== 0)
            seeks = WhereCauses;
        else
            seeks = [];
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, seeks }
        });
        this.state.diviDisplay.div1 = 'none';
        this.state.diviDisplay.div2 = '';
        this.state.diviDisplay.lable = '认定';
        this.state.diviDisplay.isRD = true;
    }
    seachHandler(data) {
        this.state.seachData = data;
    }
    render() {
        let { showEdit, record, offsetHeight } = this.props
        let height = (offsetHeight - 128) * 0.50 - 41
        let dataList = []
        Object.values(this.state.diviList).forEach(v => dataList.push(v))
        let seachDiviSource = []
        Object.values(this.state.seachDataSource).forEach(v => seachDiviSource.push(v))
        const dsCount = this.state.seachDataSource.length
        const isDisabled = dsCount > 0 ? true : false;
        const controlsCx = [
            { name: 'ACNO', required: false, type: 'text', label: '账号', grid: 4 / 24, layout: { labelSpan: 8, wrapperSpan: 16 } },
            { name: 'CUNM', required: false, type: 'text', label: '客户名称', grid: 7 / 24, layout: { labelSpan: 8, wrapperSpan: 16 } },
            { name: 'TRTD', required: false, type: 'date', label: '交易日期', grid: 7 / 24, layout: { labelSpan: 8, wrapperSpan: 16 },dataType: "date" },
            { name: 'button', required: false, type: 'button-group', grid: 6 / 24, data: [{ value: '1', label: '查询', onClick: this.showTableHandler.bind(this) }, { value: '2', label: this.state.diviDisplay.lable, onClick: this.showDiviHandler.bind(this) }], layout: { labelSpan: 4, wrapperSpan: 20 } },
        ]
        const controlsFhCx = [
            { name: 'EMID', required: true, type: 'search', label: '员工', grid: 5 / 24, layout: { labelSpan: 9, wrapperSpan: 15 }, fetch: { daoName: 'UserSel', searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.seachHandler.bind(this) }, dataType: "number", seekType: 2 },
            { name: 'DSVL', required: true, type: 'number', label: '比例%', grid: 4 / 24, layout: { labelSpan: 12, wrapperSpan: 12 }, dataType: 'number' },
            { name: 'DSDT', required: true, type: 'month', label: '月份', grid: 5 / 24, isDisabled: isDisabled, layout: { labelSpan: 9, wrapperSpan: 15 }, dataType: 'month' },
            { name: 'button', required: false, type: 'button-group', grid: 10 / 24, data: [{ value: '1', label: '添加', onClick: this.addSeachDiviHandler.bind(this) }, { value: '2', label: '删除', onClick: this.deleteSeachDiviHandler.bind(this) }, { value: '3', label: '提交', onClick: this.submitSeachDiviHandler.bind(this) }] },
        ]
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create} style={{ paddingBottom: '-16px' }}>
                        <EditFrom ref="TMinOperFrom" daoName={daoName} controls={controlsCx} record={record} clearItemMargin={true} />
                    </div>
                    <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls} height={height} />
                    <div style={{ display: this.state.diviDisplay.div2 }} id="showCompDiviDiv" >
                      <TMinDiviFrom />
                    </div>
                    <div style={{ display: this.state.diviDisplay.div1 }} id="fhCompDiviDiv">
                        <Row>
                            <Col span={9}>
                                <DataEditTable columns={columnsDv} ref="diviTable" height={150} dataSource={dataList} keyName={"ID"} daoName={daoName} canDelete={true} onDelete={this.deleteHandle.bind(this)} />
                            </Col>
                            <Col span={15}>
                                <DataEditTable columns={columnsFhDivi} dataSource={this.state.seachDataSource} ref="diviFhTable" height={150} keyName={"EMID"} daoName={"TMinDivi"} footer={false} />
                                <EditFrom ref="TMinDiviFrom" daoName={daoName} controls={controlsFhCx} record={record} clearItemMargin={true} />
                            </Col>
                        </Row>
                    </div>
                </div>
            </div>
        )
    }
}

function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, list, keyName } = state.MinOper;
    const { offsetHeight } = state.menus
    return {
        showEdit,
        selectedRowKeys,
        list,
        keyName,
        offsetHeight,
        record
    }
}
TMinOperFrom = connect(mapStateToProps)(TMinOperFrom)
export default TMinOperFrom;

let render = (props) => React.createElement(TMinOperFrom, props);
let f = new Factory()
f.set("TMinOperFrom", render)
